<?php

namespace app\admin\service;

use app\admin\validate\SetExpressValidate;
use support\spark\exception\ApiException;
use support\spark\model\system\SetExpress;

class ExpressService
{

    /**
     * 获取快递列表
     * @param $param
     * @return array
     */
    public function getList($param)
    {
        $limit = $param['limit'];
        $name = $param['name'];

        $where = [];
        if (!empty($name)) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }
        $setExpressModel = new SetExpress();
        $list=$setExpressModel->getPaginateList($where,['*'],['id'=>'desc'],[],$limit);
        return dataReturn(0, 'success', $list);
    }

    /**
     * 添加快递
     * @param $param
     * @return array
     */
    public function addExpress($param)
    {
        // 检验完整性
        $validate = new SetExpressValidate();
        if (!$validate->check($param)) {
            throw new ApiException($validate->getError(),-1);
        }
        $setExpressModel = new SetExpress();
        $has = $setExpressModel->checkUnique([
            'name' => $param['name']
        ]);

        if (!empty($has)) {
            throw new ApiException('物流公司名称已经存在',-1);
        }
        $param['create_time'] = now();
        $param['update_time'] = now();
        $setExpressModel->insertOne($param);
        return  dataReturn(0,'添加成功');
    }

    /**
     * 编辑快递
     * @param $param
     * @return array
     */
    public function editExpress($param)
    {
        // 检验完整性
        $validate = new SetExpressValidate();
        if (!$validate->check($param)) {
            throw new ApiException($validate->getError(),-1);
        }
        $setExpressModel = new SetExpress();

        $where[] = ['id', '<>', $param['id']];
        $where[] = ['name', '=', $param['name']];
        $has = $setExpressModel->checkUnique($where);

        if (!empty($has)) {
            throw new ApiException('物流公司名称已经存在',-1);
        }

        $setExpressModel->updateById($param, $param['id']);
        return  dataReturn(0,'修改成功');
    }

}